/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webaccess.retailws.Action;

import com.webaccess.retailws.Bean.FileUploadBean;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;

/**
 *
 * @author Owner
 */
public class FileUploadAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        FileUploadBean myForm = (FileUploadBean) form;

        // Process the FormFile
        FormFile myFile = myForm.getMyFile();
        String contentType = myFile.getContentType();
        String fileName = myFile.getFileName();
        int fileSize = myFile.getFileSize();
        byte[] fileData = myFile.getFileData();

        System.out.println("contentType: " + contentType);
        System.out.println("File Name: " + fileName);
        System.out.println("File Size: " + fileSize);

        //Get the servers upload directory real path name
        String filePath = getServlet().getServletContext().getRealPath("/") + "products";
        //create the upload folder if not exists
        File folder = new File(filePath);
        if (!folder.exists()) {
            folder.mkdir();
        }
        if (!("").equals(fileName)) {
            System.out.println("Server path:" + filePath);
            File newFile = new File(filePath, fileName);
            if (!newFile.exists()) {
                FileOutputStream fos = new FileOutputStream(newFile);
                fos.write(myFile.getFileData());
                fos.flush();
                fos.close();
            }
        }
        PrintWriter outFileName = response.getWriter();
        outFileName.println(fileName);
        return null;
    }
}
